<?php
/**
 * 产品促销管理模型
 * @author cjli
 *
 */
class PromotionModel extends Model
{

	/*static $bonusType = array(
		'0' => '按用户发放 ',
		'1' => '按商品发放 ',
		'2' => '按订单金额发放',
		'3' => '线下发放的红包',
	);*/
	static $bonusType = array(
		'0' => '按用户发放 ',
		'1' => '按订单金额发放 ',
		'2' => '按会员生日发放',
	);
		static $couponType = array(
		'0' => '按用户发放 ',
		'1' => '按订单金额发放 ',
		'2' => '按会员生日发放',
	);

	/**
	 * 批发列表
	 * @return array
	 */
	public static function getWholesaleList()
	{
		$wholesaleList = array();
		if(S('wholesale_list')){
			$wholesaleList = S('wholesale_list');
		}else{
			$wholesale_db = D('product_wholesale');
			$result = $wholesale_db->where('display=1')->select();
			if($result){
				foreach ($result as $whole){
					$wholesaleList[$whole['product_id']] = $whole;
				}
			}
			S('wholesale_list', $wholesaleList);
		}
		return $wholesaleList;
	}

	/**
	 * 获取产品批发信息
	 * @param int $pid 产品ID
	 * @return array
	 */
	public static function getProductWholesaleInfo($pid)
	{
		$wholesale_db = D('product_wholesale');
		$wholesale = $wholesale_db->where('product_id='.$pid)->find();
		return $wholesale ? $wholesale : false;
	}

	/**
	 * 更新批发信息
	 * @param array $post post 数据
	 * @param int $wholesale_id 批发ID
	 */
	public static function updateWholesaleInfo($post, $wholesale_id = null)
	{
		$data = array(
			'product_id' => intval($post['product_id']),
			'product_name' => trim($post['product_name']),
			'display' => intval($post['display']),
		);

		if(empty($data['product_name'])){
			$product_items_db = D('product_items');
			$where = array(
				'product_id' => $data['product_id'],
				'language_id' => C('language_id'),
			);
			$data['product_name'] = $product_items_db->where($where)->getField('name');
		}

		//等级
		if($post['rank_id']['0'] == 0){
			$data['rank_ids'] = 0;
		}else{
			$data['rank_ids'] = join(',', $post['rank_id']);
		}
		//数量价格处理
		$qtyArray = $post['qty'];
		$priceArray = $post['price'];
		$prices = array();
		foreach ($qtyArray as $key => $qty){
			if(intval($qty) == 0 || floatval($priceArray[$key]) ==0){
				continue;
			}
			$prices[] = array(
				'qty' => $qty,
				'price' => $priceArray[$key],
			);
		}
		if($prices){
			$data['prices'] = serialize($prices);
		}
		$wholesale_db = D('product_wholesale');
		if($wholesale_id){
			$wholesale_db->where('id='.$wholesale_id)->save($data);
		}else{
			$wholesale_id = $wholesale_db->add($data);
		}
		if($wholesale_id)
			S('wholesale_list', NULL);
		return $wholesale_id;
	}

	/**
	 * 根据产品ID号删除批发方案
	 * @param int $pid 产品ID
	 * @return boolean
	 */
	public static function deleteProductWholesaleInfo($pid)
	{
		$wholesale_db = D('product_wholesale');
		$wholesale_db->where('product_id='.$pid)->delete();
		S('wholesale_list', NULL);
		return;
	}


	/**
	 * 获取批发价格
	 * @param int $pid 产品ID
	 * @param int $qty 数量
	 * @param int $rank_id 会员等级
	 * @return float
	 */
	public static function getProductWholesalePrice($pid, $qty = 1, $rank_id = 0)
	{
		$price = 0;
		$wholesale_db = D('product_wholesale');
		$wholesaleInfo = $wholesale_db->where(array('display' => 1, 'product_id' => $pid))->find();
		if($wholesaleInfo){
			$wholesale_prices = unserialize($wholesaleInfo['prices']);
			//如果设置了等级
			if($wholesaleInfo['rank_ids']){
				$rank_ids = explode(',', $wholesaleInfo['rank_ids']);
				if(in_array($rank_id, $rank_ids)){
						foreach ($wholesale_prices as $val){
							if($qty >= $val['qty']){
								$price = $val['price'];
							}
						}
				}
				//没有设置等级
			}else{
				foreach ($wholesale_prices as $val){
					if($qty >= $val['qty']){
						$price = $val['price'];
					}
				}
			}
		}
		return $price;
	}

	/**
	 * 获取红包发放数量
	 * $return array
	 */
	public static function getBounsSendCount()
	{
		$bonusArray = array();
		$user_bonus_db = D('user_bonus');
		$bonusList = $user_bonus_db->field('bonus_id,count(*) AS num')->group('bonus_id')->select();
		if($bonusList){
			foreach ($bonusList as $bonus){
				$bonusArray[$bonus['bonus_id']] = $bonus['num'];
			}
		}
		return $bonusArray;
	}

	/**
	 * 获取红包使用数量
	 * $return array
	 */
	public static function getBounsUseCount()
	{
		$bonusArray = array();
		$user_bonus_db = D('user_bonus');
		$bonusList = $user_bonus_db->field('bonus_id,count(*) AS num')->where(array('used_time' => array('gt', '0')))->group('bonus_id')->select();
//		echo $user_bonus_db->getLastSql();exit;
		if($bonusList){
			foreach ($bonusList as $bonus){
				$bonusArray[$bonus['bonus_id']] = $bonus['num'];
			}
		}
		return $bonusArray;
	}

	/**
	 * 更新红包信息
	 * @param array $post post 数据
	 * @param int $wholesale_id 批发ID
	 */
	public static function updateBonusInfo($post, $bonus_id = null)
	{
		$data = array(
			'type_name' => trim($post['type_name']),
			'type_money' => floatval($post['type_money']),
			'min_goods_amount' => floatval($post['min_goods_amount']),
			'send_type' => intval($post['send_type']),
			'send_start_date' => strtotime(trim($post['send_start_date'])),
			'send_end_date' => strtotime(trim($post['send_end_date'])),
			'use_start_date' => strtotime(trim($post['use_start_date'])),
			'use_end_date' => strtotime(trim($post['use_end_date'])),
			'restrict' => intval($post['restrict']),
		);
		$bonus_db = D('bonus_type');
		if($bonus_id){
			$bonus_db->where('id='.$bonus_id)->save($data);
		}else{
			$bonus_id = $bonus_db->add($data);
		}
		if($bonus_id)
			S('bonus_list', NULL);
		return $bonus_id;
	}

	//更新优惠码的信息
		public static function updateCouponInfo($post, $coupon_id = null)
	{
                $expiration_time = isset($post['expiration_time']) && !empty($post['expiration_time']) ? strtotime($post['expiration_time']) : 2147483647 ;

                if(empty($expiration_time) ||$expiration_time>2147483647){
                    $expiration_time = 2147483647;
                }
                if($post['coupon_type'] == 2){
                    $status = 4;//折扣优惠码
                    $coupon_money = floatval($post['coupon_money2']);//优惠金额当折扣率 
                }else{
                    $coupon_money = floatval($post['coupon_money']);//优惠金额
                }
               
		$data = array(
			'coupon_code' => trim($post['coupon_code']),
			'coupon_money' => $coupon_money,
			'min_goods_amount' => floatval($post['min_goods_amount']),
			'min_amount' => floatval($post['min_amount']),
			'max_amount' => floatval($post['max_amount']),
            'expiration_time' => $expiration_time,
            'status' => isset($status) ? $status : 1,
            'favorable_group_desc' => $post['favorable_group_desc'],
		);
		$coupon_db = D('favorable');
		if($coupon_id){
			$coupon_db->where('id='.$coupon_id)->save($data);
		}else{
			$coupon_id = $coupon_db->add($data);
		}
		return $coupon_id;
	}
    
    //更新优惠码的信息
    public static function addGroupCouponInfo($post,$group_name = null)
	{

                $expiration_time = isset($post['expiration_time']) && !empty($post['expiration_time']) ? strtotime($post['expiration_time']) : 2147483647 ;

                if(empty($expiration_time) ||$expiration_time>2147483647){
                    $expiration_time = 2147483647;
                }
                if($post['coupon_type'] == 2){
                    $status = 4;//折扣优惠码
                    $coupon_money = floatval($post['coupon_money2']);//优惠金额当折扣率 
                }else{
                    $status = 2;
                    $coupon_money = floatval($post['coupon_money']);//优惠金额
                }
               
		$data = array(
//			'coupon_code' => trim($post['coupon_code']),
			'coupon_money' => $coupon_money,
			'min_goods_amount' => floatval($post['min_goods_amount']),
			'min_amount' => floatval($post['min_amount']),
			'max_amount' => floatval($post['max_amount']),
            'expiration_time' => $expiration_time,
            'status' => isset($status) ? $status : 2,
            'usage_count' => isset($post['usage_count']) ? $post['usage_count'] : 1,
            'count' => isset($post['usage_count']) ? $post['usage_count'] : 1,
            'favorable_group' => $post['favorable_group'],
            'favorable_group_desc' => $post['favorable_group_desc'],
            'type' => isset($status) ? $status : 2,
		);
        //var_dump($data);die;
            $coupon_db = D('favorable');
            $post['codes'] = trim($post['codes'], ',');
             $coupon_list = explode(',', $post['codes']);
             if(!$group_name){
                 $coupon_list = array_unique ( $coupon_list ); 
                foreach($coupon_list as $k=>$v){//看看有没有重复的优惠码
                    $coupon_code = trim($coupon_list[$k]);
                    $coupon_data = $coupon_db->where('coupon_code="'.$v.'"')->find();
                }
                if($coupon_data){
                    return false;
                }
             }
        if($group_name){
            //unset($data['usage_count']);
            $coupon_db = D('favorable');
            $where['favorable_group'] = $group_name;
            $couponInfo = $coupon_db->where($where)->order('id')->select();
            $count = $couponInfo[0]['count'];
            if($count == $data['usage_count']){
                unset($data['usage_count']);
            }
            if($couponInfo){
                foreach($coupon_list as $k=>$v){
                     unset($data['id']);
                     $data['coupon_code'] = trim($coupon_list[$k]);
                    if(!$couponInfo[$k]){
                        $data['usage_count'] = isset($post['usage_count']) ? $post['usage_count'] : 1;
                        $coupon_db->add($data);
                    }else{
                        $data['id'] = $couponInfo[$k]['id'];
                        $coupon_db->save($data);
                    }
                    $result = true;
                }
            }
        }else{
             foreach($coupon_list as $k=>$v){
                 if($v){
                 $data['coupon_code'] = trim($v);
                 $result = $coupon_db->add($data);   
                 }
             }
        }
             
             return $result;
	}

	/**
	 * 获取红包信息
	 * @param int $bonus_id 红包ID号
	 * @return array
	 */
	public static function getBonusInfo($bonus_id)
	{
		$bonus_db = D('bonus_type');
		$info = $bonus_db->find($bonus_id);
		return $info;
	}
	/**
	 * 获取优惠码信息
	 * @param int $coupon_id 优惠码ID号
	 * @return array
	 */
	public static function getCouponInfo($coupon_id)
	{
		$coupon_db = D('favorable');
		$info = $coupon_db->find($coupon_id);
		return $info;
	}
	/**
	 * 用户红包列表
	 * @return array
	 */
	public static function getBonusList($bonus_id)
	{
		$userBonusList = array();

		$user_bonus_db = D('user_bonus');
		$result = $user_bonus_db->where('bonus_id='.$bonus_id)->select();
		if($result){
			foreach ($result as $whole){
				$userBonusList[$whole['user_id']] = $whole;
			}
		}
		return $userBonusList;
	}

	/**
	 * 获取产品尺码信息
	 * @param int $pid 产品ID
	 * @return array
	 */
	public static function getProductSizeInfo($pid)
	{
		$size_db = D('product_size');
		$size = $size_db->where('product_id='.$pid)->find();
		return $size ? $size : false;
	}

	/**
	 * 更新商品尺码信息
	 * @param array $post post 数据
	 * @param int $wholesale_id 批发ID
	 */
	public static function updateSizeInfo($post, $size_id = null)
	{
		$data = array(
			'product_id' => intval($post['product_id']),
			'product_name' => trim($post['product_name']),
			'display' => intval($post['display']),
		);

		//数量价格处理
		$sizeArray = $post['size'];
		$qtyArray = $post['qty'];
		$stockArray = $post['stock'];
		$numArray = $post['num'];
		$prices = array();
		foreach ($sizeArray as $key => $size){
			if(empty($size) || floatval($qtyArray[$key]) ==0){
				continue;
			}
			$prices[] = array(
				'size' => $size,
				'qty' => $qtyArray[$key],
				'stock' => $stockArray[$key],
				'num' => $numArray[$key],
			);
		}

		if($prices){
			$data['prices'] = serialize($prices);
		}
		$size_db = D('product_size');
		if($size_id){
			$size_db->where('id='.$size_id)->save($data);
		}else{
			$size_id = $size_db->add($data);
		}
		if($size_id){
			S('size_list_'.$post['product_id'], NULL);
		}
		return $size_id;
	}

	/**
	 * 根据产品ID号删除商品尺码
	 * @param int $pid 产品ID
	 * @return boolean
	 */
	public static function deleteProductSizeInfo($pid)
	{
		$size_db = D('product_size');
		$size_db->where('product_id='.$pid)->delete();
		S('size_list', NULL);
		return;
	}
}